<?php
/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/06/26
 * Time: 下午17:55
 * @Description:  门店工位统计脚本
 */
$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();


//门店工位统计订单状态
$staion=array(
    1117,
    1217,
    1317,
    1417,
    1018,
    1219,
    1419
);
//查询所有门店工位信息
$start_time = date("Y-m-d",strtotime("-1 day"))." 00:00:00";
$start_time_now = date("Y-m-d",time())." 00:00:00";
$end_time = date("Y-m-d",strtotime("-1 day"))." 23:59:59";
$end_time_now = date("Y-m-d",time())." 23:59:59";
$lists = MaintenanceStationDetails::join('maintenance_station','maintenance_station_details.station_id','=','maintenance_station.id')
    ->join('maintenance_shops','maintenance_station_details.shop_id','=','maintenance_shops.id')
    ->join('orders','orders.order_id','=','maintenance_station_details.order_id')
    ->whereIn('orders.status',$staion)
    ->whereBetween('orders.updated_at', array($start_time, $end_time))
    ->where("occupy_end_time","!=","0000-00-00 00:00:00")
    ->select("maintenance_station_details.id","maintenance_station_details.order_id","occupy_end_time","occupy_start_time","orders.payable_amount","maintenance_station_details.car_no","year_month","maintenance_shops.name as shop_name","maintenance_shops.id as shop_id","maintenance_station.name as station_name","maintenance_station.id as station_id")
    ->get();

//处理数据，组成新数组（我们想要的数组）
//下面的所有操作都是在有数据的情况下进行，没有新数据直接返回，不需要任何操作
if(!is_null($lists)){
    //判断订单号是否一样，统计一个订单号的占用时长（与车牌号无关，只要订单号一样就放在一起）
    $item = [];
    foreach ($lists as $key => $val) {
        $temp = array(
            'order_id' => $val['order_id'],
            'id' => $val['id'],
            'occupy_end_time' => $val['occupy_end_time'],
            'occupy_start_time' => $val['occupy_start_time'],
            'payable_amount' => $val['payable_amount'],
            'car_no' => $val['car_no'],
            'year_month' => $val['year_month'],
            'shop_name' => $val['shop_name'],
            'shop_id' => $val['shop_id'],
            //'business_start_time' => $val['business_start_time'],
            //'business_end_time' => $val['business_end_time'],
            'station_name' => $val['station_name'],
            'station_id' => $val['station_id'],
        );
        $item[$val['order_id']][] = $temp;
    }

    //计算时长和金额
    foreach ($item as $k => $v) {
        $item[$k]['length_time'] = '00:00:00';
        $item[$k]['payable_amount'] ='0';
        $item[$k]['length_time_stamp'] = '0';
        foreach ($v as $kk => $vv) {
            $item[$k][$kk]['length_time'] = '00:00:00';
            $item[$k][$kk]['length_time'] = $vv['length_time'] = MaintenanceStationLengthTime::str_time($vv['occupy_start_time'], $vv['occupy_end_time'], $vv['shop_id']);
            $item[$k]['length_time'] += $item[$k][$kk]['length_time'];
            $item[$k]['payable_amount'] += $vv['payable_amount'];
        }
        $item[$k]['length_time_stamp'] = $item[$k]['length_time'];
        $item[$k]['length_time'] = MaintenanceStationLengthTime::format_date($item[$k]['length_time']);
    }
    //查询数据库，判断处理完成的数据是否存在于数据库中，没有执行全部添加，有就执行删除
    //$station = MaintenanceStationCursor::whereBetween('updated_at', array($start_time, $end_time))->get()->toArray();
    $station = MaintenanceStationCursor::where("updated_at","like","%".date("Y-m-d")."%")->get()->toArray();
    if($station){
        $tmp = [];
        foreach ($station as $_sta => $_arr) {
            $tmps = array(
                'order_id' => $_arr['order_id'],
            );
            $tmp[$_arr['order_id']][] = $tmps;
        }

        if($order = array_intersect(array_keys($item),array_keys($tmp))){

            MaintenanceStationCursor::whereIn("order_id",$order)->delete();
        }
    }

    //操作入库
    foreach($item as $_key => $_item){

        $maintenance_station_cursor = array(
            'order_id' => $_item[0]['order_id'],
            'occupy_start_time' => $_item[0]['occupy_start_time'],
            'occupy_end_time' => $_item[0]['occupy_end_time'],
            'payable_amount' => $_item['payable_amount'],
            'car_no' => $_item[0]['car_no'],
            'year_month' => $_item[0]['year_month'],
            'shop_name' => $_item[0]['shop_name'],
            'shop_id' => $_item[0]['shop_id'],
            'station_name' => $_item[0]['station_name'],
            'station_id' => $_item[0]['station_id'],
            'length_time_stamp' => $_item['length_time_stamp'],
            'length_time' => $_item['length_time'],
            'created_at' => date("Y-m-d H:i:s",time()),
            'updated_at' => date("Y-m-d H:i:s",time()),
        );

        try{
            $a = DB::table('maintenance_station_cursor')->insert($maintenance_station_cursor);
        }catch (Exception $e) {
            echo "insert into maintenance_station_cursor error\n";
            var_dump($e);
        }
    }




    //操作maintenance_station_cursor表成功，处理数据
    //同一个工位的信息放到一起去
    //$id = DB::getPdo()->lastInsertId();
    $station_list = MaintenanceStationCursor::join("maintenance_station","maintenance_station_cursor.station_id","=","maintenance_station.id")
        ->join("maintenance_station_type","maintenance_station.type","=","maintenance_station_type.id")
        ->select("maintenance_station_cursor.payable_amount","maintenance_station_cursor.year_month","maintenance_station_cursor.shop_id","maintenance_station_cursor.shop_name","maintenance_station_cursor.station_id","maintenance_station_cursor.station_name","maintenance_station_cursor.length_time","maintenance_station_cursor.length_time_stamp","maintenance_station_type.name as type_name","maintenance_station_type.id as type_id")
        //->where('maintenance_station_cursor.updated_at','like','%'.date('Y-m',time()).'%')
        ->whereBetween('maintenance_station_cursor.updated_at', array($start_time_now, $end_time_now))
        ->get()
        ->toArray();

    if($station_list){
        $item1 = [];
        foreach($station_list as $_key1 => $_val1){
            $temp1 = array(
                'payable_amount' => $_val1['payable_amount'],
                'year_month' => $_val1['year_month'],
                'shop_id' => $_val1['shop_id'],
                'shop_name' => $_val1['shop_name'],
                'station_id' => $_val1['station_id'],
                'station_name' => $_val1['station_name'],
                'length_time' => $_val1['length_time'],
                'type_name' => $_val1['type_name'],
                'type_id' => $_val1['type_id'],
                'length_time_stamp' => $_val1['length_time_stamp'],
            );
            $item1[$_val1['station_id']."_".$_val1['year_month']][] = $temp1;
        }



        $nowtime = date("d",time());
        if($nowtime == 1){
            $year_month = date("Y-m",strtotime("-1 month"));
        }else{
            $year_month = date('Y-m',time());
        }
        //计算总台次、时长、和价钱
        foreach($item1 as $_i => $_it){
            //$item1[$_i]['car_count'] = count($_it);
            $item1[$_i]['car_count'] = '0';

            $length_time = "00:00:00";
            $item1[$_i]['payable_amount'] = '0';
            $item1[$_i]['length_time'] = '00:00:00';
            $length_times ='0';
            $item1[$_i]['length_time_stamp'] = '0';
            foreach($_it as $_s => $_sa){
                $item1[$_i]['payable_amount'] += $_sa['payable_amount'];
                $length_times += $_sa['length_time_stamp'];
                $item1[$_i]['length_time_stamp'] = $length_times;
                $item1[$_i]['length_time'] = MaintenanceStationLengthTime::format_date($length_times);
                $item1[$_i]['car_count'] = MaintenanceStationDetails::join('maintenance_station','maintenance_station_details.station_id','=','maintenance_station.id')
                    ->join('maintenance_shops','maintenance_station_details.shop_id','=','maintenance_shops.id')
                    ->join('orders','orders.order_id','=','maintenance_station_details.order_id')
                    ->whereIn('orders.status',$staion)
                    ->where("occupy_end_time","!=","0000-00-00 00:00:00")
                    ->where("orders.updated_at","like","%".$year_month."%")
                    ->where("maintenance_station_details.station_id",$_sa['station_id'])
                    ->select("maintenance_station_details.id","maintenance_station_details.order_id","occupy_end_time","occupy_start_time","orders.payable_amount","maintenance_station_details.car_no","year_month","maintenance_shops.name as shop_name","maintenance_shops.id as shop_id","maintenance_station.name as station_name","maintenance_station.id as station_id")
                    ->count();
            }
        }


        //print_r($item1);die;
        foreach($item1 as $t => $tt){
            $station1 = MaintenanceStationList::where('year_month',$year_month)->where('station_id',$tt[0]['station_id'])->first();
            if($station1){
                MaintenanceStationList::where('year_month',$year_month)->where('station_id',$tt[0]['station_id'])->delete();
            }
            $maintenance_station_list = new MaintenanceStationList();
            $maintenance_station_list->year_month = $tt[0]['year_month'];
            $maintenance_station_list->shop_name = $tt[0]['shop_name'];
            $maintenance_station_list->shop_id = $tt[0]['shop_id'];
            $maintenance_station_list->station_name = $tt[0]['station_name'];
            $maintenance_station_list->station_id = $tt[0]['station_id'];
            $maintenance_station_list->type_name = $tt[0]['type_name'];
            $maintenance_station_list->type_id = $tt[0]['type_id'];
            $maintenance_station_list->station_name = $tt[0]['station_name'];
            $maintenance_station_list->car_count = $tt['car_count'];
            //$maintenance_station_list->payable_amount = $maintenance_station_list->payable_amount + $station_list['payable_amount'];
            $maintenance_station_list->payable_amount = $tt['payable_amount'];
            $maintenance_station_list->length_time = $tt['length_time'];
            $maintenance_station_list->length_time_stamp = $tt['length_time_stamp'];
            $maintenance_station_list->created_at = date("Y-m-d H:i:s", time());
            $maintenance_station_list->updated_at = date("Y-m-d H:i:s", time());
            $maintenance_station_list->save();
        }
    }






}

